from django.http import Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.views.generic import View
from comments.models import Comment
from comments.forms import CommentForm
from myblog.models import Article


# Create your views here.


class CommentView(View):
    def post(self, request, cid):
        # 这里根据传入的id获取文章内容，没有返回404页面
        article = get_object_or_404(Article, id=cid)
        form = CommentForm(request.POST)
        if form.is_valid():
            # 验证表单的合法性
            # 这里form.save()生成表单创建的评论实例，但commit=False不提交到数据库
            try:
                comment = form.save(commit=False)
                # 将评论与博客关联起来
                comment.article = article
                # 提交到数据库
                comment.save()
            except Exception as e:
                raise Http404
            # 重定向到博客详情页，
            return redirect(reverse('myblog:blog_detail', kwargs={"cid": cid}))
        else:
            # 如果验证不合法，重新渲染一下detail页面的数据
            # 查询该文章所有的评论
            try:
                comment_list = article.comment_set.all()
            except Exception as e:
                raise Http404
            context = {
                "comment_list": comment_list,
                "form": form,
                "article": article
            }
            return render(request, 'blog/detail.html', context=context)
